﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Database.Context;
using QuanLyThongTinCoSo.Common;
using Model = Database.Models;

namespace QuanLyThongTinCoSo.Biz
{
    public class PhongBiz : BaseBiz
    {
        public PhongBiz()
        {
            DbContext = new Context();
        }

        public PhongBiz(Context context)
        {
            DbContext = context;
        }

        public override void Insert(Model.BaseModel model)
        {
            var phong = model as Model.Phong;
            phong.Created = DateTime.Now;
            phong.Modified = DateTime.Now;
            phong.CreatedBy = Utilities.CurrentUser();
            phong.ModifiedBy = Utilities.CurrentUser();

            DbContext.Phongs.Add(phong);
            DbContext.SaveChanges();
        }

        public override void Update(Model.BaseModel model)
        {
            var phong = model as Model.Phong;
            phong.Modified = DateTime.Now;
            phong.ModifiedBy = Utilities.CurrentUser();

            DbContext.Entry(phong).State = EntityState.Modified;
            DbContext.SaveChanges();
        }

        public override void Delete(Model.BaseModel model)
        {
            DbContext.Phongs.Attach(model as Model.Phong);
            DbContext.Phongs.Remove(model as Model.Phong);
            DbContext.Entry(model).State = EntityState.Deleted;

            DbContext.SaveChanges();
        }

        public override void DeleteItems(List<Model.BaseModel> models)
        {
            foreach (Model.Phong phong in models)
            {
                DbContext.Phongs.Attach(phong);
                DbContext.Phongs.Remove(phong);
                DbContext.Entry(phong).State = EntityState.Deleted;
            }

            DbContext.SaveChanges();
        }

        public override Model.BaseModel GetItemById(int id)
        {
            return (from item in DbContext.Phongs
                    where item.Id == id
                    select item).Include(p => p.Dois).First();
        }

        public Model.Phong GetRoleByName(string phongName)
        {
            return DbContext.Phongs.FirstOrDefault(p => p.TenPhong == phongName);
        }

        #region GetAll

        public List<Model.Phong> GetAll()
        {
            return DbContext.Phongs.OrderBy(p => p.TenPhong).Include(p => p.Dois).ToList();
        }

        #endregion
    }
}